/*
 * Copyright (C) 2013 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.squareup.picasso;

import ohos.agp.components.Component;
import ohos.agp.components.Image;

import java.lang.ref.WeakReference;

public class DeferredRequestCreator implements Component.BindStateChangedListener {

    private final RequestCreator creator;
    final WeakReference<Image> target;
    Callback callback;

    DeferredRequestCreator(RequestCreator creator, Image target, Callback callback) {
        this.creator = creator;
        this.target = new WeakReference<>(target);
        this.callback = callback;

        target.setBindStateChangedListener(this);

        // Only add the pre-draw listener if the view is already attached.
        // See: https://github.com/square/picasso/issues/1321
        if (target.getTag() != null) {
            onComponentBoundToWindow(target);
        }
    }

    void cancel() {
        creator.clearTag();
        callback = null;

        Image target = this.target.get();
        if (target == null) {
            return;
        }
        this.target.clear();

        target.removeBindStateChangedListener(this);
    }

	@Override
    public void onComponentBoundToWindow(Component component) {
        onPreDraw();
    }

    @Override
    public void onComponentUnboundFromWindow(Component component) {
    }


    public boolean onPreDraw() {
        Image target = this.target.get();
        if (target == null) {
            return true;
        }
        int width = target.getWidth();
        int height = target.getHeight();

        if (width <= 0 || height <= 0) {
            return true;
        }

        target.removeBindStateChangedListener(this);
        this.target.clear();
        this.creator.unfit().resize(width, height).into(target, callback);
        return true;
    }

    Object getTag() {
        return creator.getTag();
    }
}
